package com.lanmaoly.web.common.exception;

import com.lanmaoly.web.common.response.CommonCode;
import com.lanmaoly.web.common.response.ResponseResult;
import com.lanmaoly.web.server.entity.Result;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import java.io.IOException;

/**
 * 异常处理器
 *
 * @author Administrator
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(ArbitrationException.class)
    public ResponseResult handleRRException(ArbitrationException e) {
        logger.error("customize Exception error code:{}msg:{}", e.getCode(), e.getMsg());
        return new ResponseResult(e.getCommonCode());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ResponseResult handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error("DuplicateKeyException error msg:{}", e.getMessage(), e);
        return new ResponseResult(CommonCode.FAIL);
    }

    @ExceptionHandler(FileUploadException.class)
    public ResponseResult handleFileUploadException(FileUploadException e) {
        logger.error("FileUploadException error msg:{}", e.getMessage(), e);
        return new ResponseResult(CommonCode.FAIL);
    }

    @ExceptionHandler(MultipartException.class)
    public ResponseResult handleMultipartException(MultipartException e) {
        logger.error("MultipartException error msg:{}", e.getMessage(), e);
        return new ResponseResult(CommonCode.FAIL);
    }

    @ExceptionHandler(Exception.class)
    public ResponseResult handleException(Exception e) {
        logger.error("Exception error msg:{}", e.getMessage(), e);
        return new ResponseResult(CommonCode.FAIL);
    }

    @ExceptionHandler(IOException.class)
    public ResponseResult handleIOException(IOException e) {
        logger.error("IOException error msg:{}", e.getMessage(), e);
        return new ResponseResult(CommonCode.FAIL);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);
        return Result.fail("请正确填写每一项");
    }

    @ExceptionHandler(BindException.class)
    public Result BindException(BindException e) {
        logger.error(e.getMessage(), e);
        return Result.fail("请正确填写每一项");
    }
}
